# -*- coding: utf-8 -*-
from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse
from django.views.decorators.csrf import csrf_exempt

from utils.encrypt import uid
from utils.tencent.cos import upload_file
from web import models
from web.forms.wiki import WikiForm


def wiki(request, project_id):
    """
    首页
    """
    
    wiki_id = request.GET.get('wiki_id')
    
    # 如果传递的有不是数值 或没传 不给看
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')
    
    obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    
    return render(request, 'wiki.html', {'wiki_obj': obj})


def wiki_add(request, project_id):
    """
    添加
    """
    if request.method == 'GET':
        form = WikiForm(request)
        return render(request, 'wiki_form.html', {'form': form})
    
    form = WikiForm(request, request.POST)
    if form.is_valid():
        
        # 在保存前判断文章的深度
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        
        form.instance.project = request.tracer.project
        form.save()
        
        return redirect(reverse('web:wiki', kwargs={'project_id': project_id}))
    
    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """
    wiki catalog
    """
    
    # 当前项目的使用wiki
    # 返回元组（1, 'hhh', 1）
    # data = models.Wiki.objects.filter(project=request.tracer.project).values_list('id', 'title', 'parent_id')
    # 返回字典 {id: 1, title: 'hhh', project_id: 1}
    # data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id')
    data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id').order_by(
        'depth', 'id')
    # data 为QuerySet，转换成序列
    data = list(data)
    print(data)
    return JsonResponse({'status': True, 'data': data})


def wiki_delete(request, project_id, wiki_id):
    """删除文档"""
    
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return redirect(reverse('web:wiki', kwargs={'project_id': project_id}))


def wiki_edit(request, project_id, wiki_id):
    """编辑文档"""
    
    obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not obj:
        return redirect(reverse('web:wiki', kwargs={'project_id': project_id}))
    
    if request.method == 'GET':
        form = WikiForm(request, instance=obj)
        return render(request, 'wiki_form.html', {'form': form})
    
    form = WikiForm(request, data=request.POST, instance=obj)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('web:wiki', kwargs={'project_id': project_id})
        preview_url = '{0}?wiki_id={1}'.format(url, wiki_id)
        return redirect(preview_url)
    return render(request, 'wiki_form.html', {'form': form})


# @csrf_exempt:是一个装饰器，添加后说明该请求该视图函数的请求可以不写的带csrf token
@csrf_exempt
def wiki_upload(request, project_id):
    """处理markdown上传的图片"""

    res = {
        'success': 0,
        'message': None,
        'url': None
    }
    print(request.FILES)
    # 获取上传的文件对象
    img_obj = request.FILES.get('editormd-image-file')
    
    # 是否获取到文件对象
    if not img_obj:
        res['message'] = '文件未上传'
        return JsonResponse(res)
    
    # 获取图片格式后缀
    ext = img_obj.name.rsplit('.')[-1]
    # 获取文件名
    key = '{}.{}'.format(uid(request.tracer.user.phone), ext)
    
    # 上传
    img_url = upload_file(request.tracer.project.bucket, request.tracer.project.region, img_obj, key)
    
    # 响应数据给markdown
    res['success'] = 1
    res['message'] = '上传成功'
    res['url'] = img_url
    
    return JsonResponse(res)

